/**
 * Copyright (C)  2011  chen wei hua.
 * Permission is granted to copy, distribute and/or modify this document
 * under the terms of the GNU Free Documentation License, Version 2.0
 * or any later version published by the Free Software Foundation;
 * with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
 * A copy of the license is included in the section entitled "GNU Free Documentation License".
 */
package com.javaeye.common.util;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

/**
 * 取得hibernate数据库操作session的帮助类
 * @author chen
 *
 */
public class HibernateUtil {

	/**
	 * hibernate数据库操作session的工厂
	 */
	//private static final SessionFactory factory;
	
	/**
	 * 
	 */
	/*static {
		try {
			Configuration config = new Configuration().configure();
			factory = config.buildSessionFactory();
		} catch (Throwable ex) {
			throw new ExceptionInInitializerError(ex);
		}
	}*/
	
	/**
	 * 与线程关联的session
	 */
	private static final ThreadLocal<Session> session = 
		new ThreadLocal<Session>();
	
	/**
	 * 取得当前线程内的session
	 * @return session
	 * @throws HibernateException
	 */
	public static Session currentSession(SessionFactory factory) throws HibernateException {
		Session s = session.get();
		if (s == null) {
			s = factory.openSession();
			session.set(s);
		}
		return s;
	}
	
	/**
	 * 关闭当前线程内的session
	 * @throws HibernateException
	 */
	public static void closeSession() throws HibernateException {
		Session s = session.get();
		session.set(null);
		if (s != null)
			s.close();
	}
}
